package com.lemon.smartsafetynew.ui.activity.hidden;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenBo;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenDownloadVo;
import com.lemon.smartsafetynew.net.services.SafeHiddenServices;
import com.lemon.smartsafetynew.util.common.CheckAppExist;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.common.UrlFormatUtils;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.TimeFormatConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Andrew on 2017/11/2.
 */

public class SafeHiddenGenerateDocumentActivity extends SwipeBackActivity {

    @Bind(R.id.content_layout)
    LinearLayout contentLayout;
    @Bind(R.id.bottom_button)
    Button bottomButton;
    @Bind(R.id.waring_tips_tv)
    TextView waringTipsTv;

    /**
     * 现场意见书
     */
    private TextView mainProblem;
    private MaterialEditText checkTwoEt;
    private MaterialEditText checkThreeEt;
    private MaterialEditText checkFourEt;
    private RadioGroup radioGroup;
    private RadioButton radioButtonOne;
    private RadioButton radioButtonTwo;
    private RadioButton radioButtonThree;

    /**
     * 责令整改书
     */
    private LinearLayout problemLayout;
    private LinearLayout editLayout;
    private ImageView editPlus;
    private MaterialEditText govOneEdit;
    private MaterialEditText govTwoEdit;
    private MaterialEditText courtEdit;

    /**
     * 复查意见书
     */
    private TextView reviewDateTv;
    private LinearLayout reviewDateLayout;
    private MaterialEditText decisionEt;
    private MaterialEditText reviewSuggestionEt;

    private static String docType = "";
    private static SafeHiddenDownloadVo safeHiddenDownloadVo;

    private String downloadUrl = "";


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {

            if (bundle.containsKey(KeyConstants.KEY_DOC_TYPE)) {
                docType = bundle.getString(KeyConstants.KEY_DOC_TYPE);
            }

            if (bundle.containsKey(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO)) {
                safeHiddenDownloadVo = (SafeHiddenDownloadVo) bundle.getSerializable(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO);
            }
        }
    }

    @Override
    protected void initTitle() {
        if (SafeHiddenBo.Doc.site_inspection_doc.getValue().equals(docType)) {
            this.setBarTitle(SafeHiddenBo.Doc.site_inspection_doc.getDesc());
        } else if (SafeHiddenBo.Doc.order_rectification_doc.getValue().equals(docType)) {
            this.setBarTitle(SafeHiddenBo.Doc.order_rectification_doc.getDesc());
        } else if (SafeHiddenBo.Doc.rectification_review_doc.getValue().equals(docType)) {
            this.setBarTitle(SafeHiddenBo.Doc.rectification_review_doc.getDesc());
        }
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(SafeHiddenGenerateDocumentActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_hidden_generate_document;
    }

    @Override
    protected void initViews() {
        super.initViews();

        waringTipsTv.setVisibility(View.GONE);
        if (SafeHiddenBo.Doc.site_inspection_doc.getValue().equals(docType)) {
            siteInspection();
        } else if (SafeHiddenBo.Doc.order_rectification_doc.getValue().equals(docType)) {
            orderRectification();
        } else if (SafeHiddenBo.Doc.rectification_review_doc.getValue().equals(docType)) {
            rectificationReview();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_GENERATE_SITE_INSPECTION_DOC.equals(event.getTag())) {                 //生成现场检查意见书
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    downloadUrl = (String) event.getObj();
                    if (downloadUrl != null) {
                        waringTipsTv.setVisibility(View.VISIBLE);
                        bottomButton.setText("打印文书");
                        bottomButton.setBackgroundColor(Color.parseColor("#FF60CC86"));
                    }
                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }
        } else if (KeyConstants.URL_GENERATE_ORDER_RECTIFICATION_DOC.equals(event.getTag())) {      //生成责令限期整改指令书
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    downloadUrl = (String) event.getObj();
                    if (downloadUrl != null) {
                        waringTipsTv.setVisibility(View.VISIBLE);
                        bottomButton.setText("打印文书");
                        bottomButton.setBackgroundColor(Color.parseColor("#FF60CC86"));
                    }
                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }
        } else if (KeyConstants.URL_GENERATE_RECTIFICATION_REVIEW_DOC.equals(event.getTag())) {     //生成整改复查意见书
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    downloadUrl = (String) event.getObj();
                    if (downloadUrl != null) {
                        waringTipsTv.setVisibility(View.VISIBLE);
                        bottomButton.setText("打印文书");
                        bottomButton.setBackgroundColor(Color.parseColor("#FF60CC86"));
                    }
                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }
        } else if (KeyConstants.URL_ORDER_RECTIFICATION_PROBLEM.equals(event.getTag())) {           //主要问题和检查意见列表
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                if (event.getEventResult() == Constants.Result.SUCCESS) {

                    List<String> prList = (List<String>) event.getObj();

                    if (SafeHiddenBo.Doc.site_inspection_doc.getValue().equals(docType)) {

                        if (prList != null && !prList.isEmpty()) {

                            mainProblem.setText(prList.get(0));

//                            for (int i = 1; i < prList.size(); i++) {
//                                if (i == 1) {
//                                    checkTwoEt.setText(prList.get(i));
//                                } else if (i == 2) {
//                                    checkThreeEt.setText(prList.get(i));
//                                } else if (i == 3) {
//                                    checkFourEt.setText(prList.get(i));
//                                }
//                            }

                        }

                    } else if (SafeHiddenBo.Doc.order_rectification_doc.getValue().equals(docType)) {

                        if (prList != null && !prList.isEmpty()) {

                            for (String pr : prList) {

                                if (!StringUtils.isEmpty(pr)) {
                                    LayoutInflater layoutInflater = LayoutInflater.from(SafeHiddenGenerateDocumentActivity.this);
                                    View viewProblem = layoutInflater.inflate(R.layout.layout_checkbox, null);
                                    problemLayout.addView(viewProblem);

                                    CheckBox checkBox = (CheckBox) viewProblem.findViewById(R.id.check_box);
                                    checkBox.setText(pr);
                                    checkBox.setChecked(true);
                                }

                            }

                            editPlus.setVisibility(View.VISIBLE);

                        }

                    }

                } else {
                    mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {

                        }
                    });
                }
            }
        }

    }

    /**
     * 现场检查书页面
     */
    private void siteInspection() {

        LayoutInflater layoutInflater = LayoutInflater.from(SafeHiddenGenerateDocumentActivity.this);
        View view = layoutInflater.inflate(R.layout.layout_site_inspection_doc, null);
        contentLayout.addView(view);

        mainProblem = (TextView) view.findViewById(R.id.main_problem);
        checkTwoEt = (MaterialEditText) view.findViewById(R.id.check_two_et);
        checkThreeEt = (MaterialEditText) view.findViewById(R.id.check_three_et);
        checkFourEt = (MaterialEditText) view.findViewById(R.id.check_four_et);
        radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);

        radioButtonOne = (RadioButton) radioGroup.getChildAt(0);
        radioButtonTwo = (RadioButton) radioGroup.getChildAt(1);
        radioButtonThree = (RadioButton) radioGroup.getChildAt(2);

        radioButtonThree.setChecked(true);

        getProblemList();

    }

    /**
     * 责令限期整改指令书页面
     */
    private void orderRectification() {

        LayoutInflater layoutInflater = LayoutInflater.from(SafeHiddenGenerateDocumentActivity.this);
        View view = layoutInflater.inflate(R.layout.layout_order_rectification, null);
        contentLayout.addView(view);

        problemLayout = (LinearLayout) view.findViewById(R.id.problem_layout);
        editLayout = (LinearLayout) view.findViewById(R.id.edit_layout);
        editPlus = (ImageView) view.findViewById(R.id.edit_plus);

        govOneEdit = (MaterialEditText) view.findViewById(R.id.gov_one_edit);
        govTwoEdit = (MaterialEditText) view.findViewById(R.id.gov_two_edit);
        courtEdit = (MaterialEditText) view.findViewById(R.id.court_edit);

        editPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editView();
            }
        });

        getProblemList();

    }

    /**
     * 整改复查意见书页面
     */
    private void rectificationReview() {

        LayoutInflater layoutInflater = LayoutInflater.from(SafeHiddenGenerateDocumentActivity.this);
        View view = layoutInflater.inflate(R.layout.layout_rectification_review, null);
        contentLayout.addView(view);

        reviewDateTv = (TextView) view.findViewById(R.id.review_date_tv);
        reviewDateLayout = (LinearLayout) view.findViewById(R.id.review_date_layout);
        decisionEt = (MaterialEditText) view.findViewById(R.id.decision_et);
        reviewSuggestionEt = (MaterialEditText) view.findViewById(R.id.review_suggestion_et);

        reviewDateLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickCheckDate();
            }
        });

    }

    /**
     * 验证责令限期整改指令书表单
     */
    private boolean verifyOrderRectification() {

        int checked = 0;
        for (int i = 0; i < problemLayout.getChildCount(); i++) {
            CheckBox checkBox = (CheckBox) problemLayout.getChildAt(i);
            if (checkBox.isChecked()) {
                checked++;
            }
        }
        for (int j = 0; j < editLayout.getChildCount(); j++) {
            LinearLayout linearLayout = (LinearLayout) editLayout.getChildAt(j);
            if (linearLayout.getChildAt(0) instanceof CheckBox) {
                CheckBox checkBox = (CheckBox) linearLayout.getChildAt(0);
                if (linearLayout.getChildAt(1) instanceof MaterialEditText) {
                    MaterialEditText editText = (MaterialEditText) linearLayout.getChildAt(1);
                    if (!"".equals(editText.getText().toString().trim())) {
                        if (checkBox.isChecked()) {
                            checked++;
                        }
                    } else {
                        mHUDUtil.showErrorTip("新增责令整改问题不能为空");
                        return false;
                    }
                }
            }
        }
        if (checked == 0) {
            mHUDUtil.showErrorTip("必须勾选责令整改问题");
            return false;
        }

        if (StringUtils.isEmpty(govOneEdit.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请填写复议的人民政府");
            return false;
        }

        if (StringUtils.isEmpty(govTwoEdit.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请填写复议的机构");
            return false;
        }

        if (StringUtils.isEmpty(courtEdit.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请填写行政诉讼的人民法院");
            return false;
        }

        return true;
    }

    /**
     * 验证复查意见书表单
     */
    private boolean verifyRectificationReview() {

        if (StringUtils.isEmpty(reviewDateTv.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请填写复查日期");
            return false;
        }

        if (StringUtils.isEmpty(decisionEt.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请填写复查决定");
            return false;
        }

        if (StringUtils.isEmpty(reviewSuggestionEt.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请填写复查意见");
            return false;
        }

        return true;
    }


    /**
     * 选择复查日期
     */
    private void pickCheckDate() {
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

                Calendar calendar = Calendar.getInstance();
                calendar.set(year, monthOfYear, dayOfMonth);
                SimpleDateFormat dateFormat = new SimpleDateFormat(TimeFormatConstants.FORMAT_DATE2, Locale.getDefault());
                String dateStr = dateFormat.format(calendar.getTime());

                reviewDateTv.setText(CommonUtil.avoidNullString(dateStr));

            }
        }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
        dpd.setThemeDark(false);
        dpd.vibrate(false);
        dpd.show(getFragmentManager(), Constants.DIALOG_TAG_CHECK_DATE);
    }

    /**
     * 责令整改文书新增编辑
     */
    private void editView() {

        LayoutInflater layoutInflater = LayoutInflater.from(SafeHiddenGenerateDocumentActivity.this);
        final View viewEdit = layoutInflater.inflate(R.layout.layout_checkbox_edittext, null);
        editLayout.addView(viewEdit);

        CheckBox checkBox = (CheckBox) viewEdit.findViewById(R.id.checkbox_edit);
        //MaterialEditText editText = (MaterialEditText) viewEdit.findViewById(R.id.opinion_edit);
        ImageView imageView = (ImageView) viewEdit.findViewById(R.id.del_image);

        checkBox.setChecked(true);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editLayout.removeView(viewEdit);
            }
        });

    }


    /**
     * 生成现场检查意见书
     */
    private void generateSiteInspection() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("user_id", AccountUtil.getUserID());
        params.put("user_name", AccountUtil.getUserName());
        params.put("danger_id", safeHiddenDownloadVo.getId());

        String suggestion = "";
        if (radioButtonOne.isChecked()) {
            suggestion = SafeHiddenBo.HandleSuggestion.within_a_limit_time.getValue();
        } else if (radioButtonTwo.isChecked()) {
            suggestion = SafeHiddenBo.HandleSuggestion.real_time.getValue();
        } else if (radioButtonThree.isChecked()) {
            suggestion = SafeHiddenBo.HandleSuggestion.self_timed_rectification.getValue();
        }

        List<String> list = new ArrayList<>();

        if (!StringUtils.isEmpty(checkTwoEt.getText().toString().trim())) {
            list.add(checkTwoEt.getText().toString().trim());
        }

        if (!StringUtils.isEmpty(checkThreeEt.getText().toString().trim())) {
            list.add(checkThreeEt.getText().toString().trim());
        }

        if (!StringUtils.isEmpty(checkFourEt.getText().toString().trim())) {
            list.add(checkFourEt.getText().toString().trim());
        }

        /**
         * @data 检查意见
         * @suggestion 处理意见（单选框）
         */
        params.put("data", new Gson().toJson(list));
        params.put("suggestion", suggestion);

        //Log.v("yxy", "【generateSiteInspection】 params = " + params);

        SafeHiddenServices
                .init()
                .generateSiteInspectionDoc(params);

    }


    /**
     * 生成责令限期整改指令书
     */
    private void generateOrderRectification() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("user_id", AccountUtil.getUserID());
        params.put("user_name", AccountUtil.getUserName());
        params.put("danger_id", safeHiddenDownloadVo.getId());

        List<String> list = new ArrayList<>();
        List<String> listProblem = new ArrayList<>();

        for (int i = 0; i < problemLayout.getChildCount(); i++) {

            CheckBox checkBox = (CheckBox) problemLayout.getChildAt(i);
            if (checkBox.isChecked()) {
                list.add(String.valueOf(i + 1));
            }

            listProblem.add(checkBox.getText().toString().trim());

        }

        for (int j = 0; j < editLayout.getChildCount(); j++) {
            LinearLayout linearLayout = (LinearLayout) editLayout.getChildAt(j);
            if (linearLayout.getChildAt(0) instanceof CheckBox) {
                CheckBox checkBox = (CheckBox) linearLayout.getChildAt(0);
                if (linearLayout.getChildAt(1) instanceof MaterialEditText) {
                    MaterialEditText editText = (MaterialEditText) linearLayout.getChildAt(1);
                    if (!"".equals(editText.getText().toString().trim())) {

                        if (checkBox.isChecked()) {
                            list.add(String.valueOf(problemLayout.getChildCount() + j + 1));
                        }

                        listProblem.add(editText.getText().toString().trim());
                    }
                }
            }
        }

        //Log.e("yxy", "listProblem = " + new Gson().toJson(listProblem));
        //Log.e("yxy", "list = " + new Gson().toJson(list));

        /**
         * @q_list 整改问题列表
         * @q_nums 整改哪几项问题
         * @rmzf 复议人民政府
         * @rmzf2 复议机构2
         * @rmfy 人民法院提出诉讼
         */
        params.put("q_list", new Gson().toJson(listProblem));
        params.put("q_nums", new Gson().toJson(list));
        params.put("rmzf", govOneEdit.getText().toString().trim());
        params.put("rmzf2", govTwoEdit.getText().toString().trim());
        params.put("rmfy", courtEdit.getText().toString().trim());

        //Log.v("yxy", "【generateOrderRectification】 params = " + params);

        SafeHiddenServices
                .init()
                .generateOrderRectificationDoc(params);

    }

    /**
     * 生成整改复查意见书
     */
    private void generateRectificationReview() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("user_id", AccountUtil.getUserID());
        params.put("user_name", AccountUtil.getUserName());
        params.put("danger_id", safeHiddenDownloadVo.getId());

        /**
         * @date 责令整改的时间
         * @decision 作出的决定
         * @opinion 复查的意见
         */
        params.put("date", reviewDateTv.getText().toString().trim());
        params.put("decision", decisionEt.getText().toString().trim());
        params.put("opinion", reviewSuggestionEt.getText().toString().trim());

        //Log.v("yxy", "【generateRectificationReview】 params = " + params);

        SafeHiddenServices
                .init()
                .generateRectificationReviewDoc(params);

    }

    /**
     * 获取问题列表
     */
    private void getProblemList() {

        LemonRequestParams params = new LemonRequestParams("");
        params.put("danger_id", safeHiddenDownloadVo.getId());

        SafeHiddenServices
                .init()
                .getOrderRectificationProblemList(params);

    }

    /**
     * 打印文书
     */
    private void printFile(String fileUrl, String fileName) {
        OkHttpUtils
                .get()
                .url(UrlFormatUtils.formatFiles(fileUrl))
                .build()
                .execute(new FileCallBack(FileUtil.getAppDocTempDir(SafeHiddenGenerateDocumentActivity.this), fileName) {

                    @Override
                    public void onError(Call call, Exception e) {
                        mHUDUtil.showErrorTip("获取文件失败。");
                    }

                    @Override
                    public void onResponse(File response) {
                        mHUDUtil.hidden();
                        callPrinter(response);
                    }

                    @Override
                    public void inProgress(float progress, long total) {

                    }
                });
    }

    @OnClick(R.id.bottom_button)
    public void onViewClicked() {

        if ("生成文书".equals(bottomButton.getText().toString().trim())) {

            if (SafeHiddenBo.Doc.site_inspection_doc.getValue().equals(docType)) {
                generateSiteInspection();
            } else if (SafeHiddenBo.Doc.order_rectification_doc.getValue().equals(docType)) {
                if (verifyOrderRectification()) {
                    generateOrderRectification();
                }
            } else {
                if (verifyRectificationReview()) {
                    generateRectificationReview();
                }
            }

        } else if ("打印文书".equals(bottomButton.getText().toString().trim())) {
            /**
             * 永远只有一份pdf保存在本地
             */
            if (CheckAppExist.checkCanonPrinterExist(SafeHiddenGenerateDocumentActivity.this)) {
                mHUDUtil.showHUD();
                printFile(downloadUrl, "doc.pdf");
            } else {
                getPrinterApk();
            }

        }
    }
}
